import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import legacy from '@vitejs/plugin-legacy'
import { version } from './package.json'

// https://vite.dev/config/
export default defineConfig({
  base: './',
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
    legacy({  // 2.需要加上此处
      targets: ["defaults", "not IE 11"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"]
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  build: {
    outDir: `dist/${version}`,
    chunkSizeWarningLimit: 4096,
    rollupOptions: {
      output: {
        assetFileNames(assetsInfo) {
          const patterns: [RegExp, string][] = [
            [/\.css$/, 'css/[name][extname]'],
            [/\.(png|jpe?g|gif|bmp|svg)$/, 'img/[name][extname]'],
            [/\.(ttf|woff2?|eot|otf)$/, 'font/[name][extname]']
          ]
          const matchedPattern = patterns.find(([regex]) =>
            regex.test(assetsInfo.name!)
          )?.[1]
          return matchedPattern || '[name][extname]'
        },
        entryFileNames(chunkInfo) {
          return 'js/[name].js'
        },
        // 保持components目录结构
        chunkFileNames: (chunkInfo) => {
          const pathPatterns: [string, string][] = [
            ['/components/', 'js/components/[name].js'],
            ['/views/', 'js/views/[name].js'],
            ['/stores/', 'js/stores/[name].js'],
            ['/config/', 'js/config/[name].js'],
            ['/directives/', 'js/directives/[name].js'], // 统一小写
            ['/utils/', 'js/utils/[name].js']
          ]

          // 统一处理路径分隔符（兼容Windows）
          const normalizedIds = chunkInfo.moduleIds.map(id =>
            id.replace(/\\/g, '/').toLowerCase()
          )

          // 使用find进行模式匹配
          const matchedPattern = pathPatterns.find(([pathSegment]) =>
            normalizedIds.some(id => id.includes(pathSegment))
          )

          return matchedPattern?.[1] || 'js/[name].js'
        }
      }
    }
  },
  server: {
    // headers: {
    //   'Access-Control-Allow-Origin': '*',
    // },
    host: '0.0.0.0',
    port: 8080,
    hmr: true
  }
})
